$(document).ready(function(){
	ui.block();
	if($(".create-new-rule").length >= 1){
		$('title').html("Rule Settings")
	}
	
	// workflow_actions.field_trigger_custom();




























	//CREATE NEW RULE
	if($(".create-new-rule").length >= 1){
		$(".create-new-rule").on("click",function(){
			RuleDialog({
				action_button:[
					'<input type="button" class="btn-blueBtn fl-margin-right save_rule" data-form-type="middleware-rule-settings" id="save_rule" value="Save" / >'
				]
			},function(){
				$('.content-dialog-scroll2').perfectScrollbar();
				var self_dialog = $(this);
				//fixes ui
				self_dialog.find('#action-advance-settings-tabs').tabs();
				$( "#accordion" ).accordion({
				    heightStyle: "fill"
				});
				$(".ui-accordion-content").css({
		            "height":"auto",
		            "font-size":"11px",
		        })
				self_dialog.find('.mid_rule_date_exe').each(function(){
					$(this).datetimepicker({
	                    changeMonth: true,
	                    dateFormat: 'yy-mm-dd'
	                });
				});

				if($("[name='schedule_opts']").length >= 1){
					$("[name='schedule_opts']").on("change",function(){
						var dis_ele = $(this);
						var dis_val = dis_ele.val();
						var dis_checked = dis_ele.prop("checked");
						if(dis_checked){

							if(dis_val == "one_time"){
								$(".container-selected-opts").hide();
								$(".selected-one-time").show();
							}else if(dis_val == "more_than_day"){
								$(".container-selected-opts").hide();
								$(".selected-more-than-day").show();
							}else if(dis_val == "daily"){
								$(".container-selected-opts").hide();
								$(".selected-daily").show();
							}else if(dis_val == "weekly"){
								$(".container-selected-opts").hide();
								$(".selected-weekly").show();
							}else if(dis_val == "monthly"){
								$(".container-selected-opts").hide();
								$(".selected-monthly").show();
							}
						}
					});
				}

				//get form name lits ajax
				getFormLists(function(){
					var json_p = this;
					var collect_append_option = '<option>--Select--</option>';
				    for (var c in json_p) {
				        collect_append_option
				                += '<option frm-id="' + json_p[c]["wsID"] + '" active-fields="' + json_p[c]["active_fields"] + '" value="' + json_p[c]["wsID"] + '" >' + json_p[c]["form_name"] + '</option>';
				    }
				    self_dialog.find(".mid_rule_sel_formname").html(collect_append_option);
				    self_dialog.find(".getFromsLoader").fadeOut(function(){
				    	$(".mid_rule_sel_formname").fadeIn();
				    	$(this).remove();
				    });

				    

				    self_dialog.find(".mid_rule_sel_formname").on("change",function(){
				    	// alert($(this).val())
				    	var dis_self = $(this);
				    	// alert(dis_self.children("option:selected").attr('active-fields'))
				    	var str_active_flds = dis_self.children("option:selected").attr('active-fields');
				    	if(str_active_flds){
				    		var spl_active_flds = str_active_flds.split(",");
					    	var collect_active_flds = "";
					    	collect_active_flds += '<option value="TrackNo">TrackNo</option>';
					    	for(var i in spl_active_flds){
					    		collect_active_flds += '<option value="'+spl_active_flds[i]+'">'+spl_active_flds[i]+'</option>';
					    	}
							if($('.workflow-ref-field').length >= 1 ){
								$('.workflow-ref-field').each(function(){
									$(this).html(collect_active_flds);
								});
							}
							if($('.workflow-trigger-fields-filter').length >= 1){
								$('.workflow-trigger-fields-filter').each(function(){
									$(this).html(collect_active_flds);
								});
							}
							if($('.workflow-trigger-fields-update').length >= 1){
								$('.workflow-trigger-fields-update').each(function(){
									$(this).html(collect_active_flds);
								});
							}
							$(".middlewareFormFields").val(spl_active_flds);
				    	}
				    });

					self_dialog.find(".mid_rule_sel_formname").trigger("change"); //this must be the last 

				});

				if(workflow_actions){
					//trigger functions
					workflow_actions.updateTrigger();
					workflow_actions.updateFieldReference();

					$(".fields_formula_row").show();
				}

				//save
				self_dialog.find(".save_rule").on("click",SaveRule);
			});
		});
	}



























	//EDIT UPDATE RULE
	$("body").on("click",".updateRules",function(){
		var self_row_click = $(this);
		var row_click_data = self_row_click.parents("tr").eq(0).data("row_data");
		if(typeof row_click_data["actions"] === "string"){
			row_click_data["actions"] = JSON.parse(row_click_data["actions"]);
		}
		if(typeof row_click_data["schedule_rep_data"] === "string" && row_click_data["schedule_rep_data"] !== ""){
			row_click_data["schedule_rep_data"] = JSON.parse(row_click_data["schedule_rep_data"]);
		}

		console.log("ROW CLICK DATA",row_click_data);

		RuleDialog({
			action_button:[
				'<input type="button" class="btn-blueBtn fl-margin-right update_rule" data-form-type="middleware-rule-settings" id="update_rule" value="Update" / >'
			]
		},function(){
			var self_dialog = $(this);

			self_dialog.data("data_clicked",row_click_data);
			self_dialog.data("row_selector",self_row_click.parents("tr").eq(0));
			
			//ui fixes 
			self_dialog.find('#action-advance-settings-tabs').tabs();

			$( "#accordion" ).accordion({
			    heightStyle: "fill"
			});
			$(".ui-accordion-content").css({
	            "height":"auto",
	            "font-size":"11px",
	        })

			self_dialog.find('.mid_rule_date_exe').each(function(){
				$(this).datetimepicker({
                    changeMonth: true,
                    dateFormat: 'yy-mm-dd'
                });
			});

			if($("[name='schedule_opts']").length >= 1){
				$("[name='schedule_opts']").on("change",function(){
					var dis_ele = $(this);
					var dis_val = dis_ele.val();
					var dis_checked = dis_ele.prop("checked");
					if(dis_checked){

						if(dis_val == "one_time"){
							$(".container-selected-opts").hide();
							$(".selected-one-time").show();
						}else if(dis_val == "more_than_day"){
							$(".container-selected-opts").hide();
							$(".selected-more-than-day").show();
						}else if(dis_val == "daily"){
							$(".container-selected-opts").hide();
							$(".selected-daily").show();
						}else if(dis_val == "weekly"){
							$(".container-selected-opts").hide();
							$(".selected-weekly").show();
						}else if(dis_val == "monthly"){
							$(".container-selected-opts").hide();
							$(".selected-monthly").show();
						}
					}
				});
			}
			var arrftrigger = row_click_data["actions"].filter(function(val, index){
				if(val['name']){
					if(val['name']=='ftrigger'){
						return true;
					}
				}
				return false;
			})
		
			var arretrigger = row_click_data["actions"].filter(function(val, index){
				if(val['name']){
					if(val['name']=='etrigger'){
						return true;
					}
				}
				return false;
			})
			
			var arrsmstrigger = row_click_data["actions"].filter(function(val, index){
				if(val['name']){
					if(val['name']=='smstrigger'){
						return true;
					}
				}
				return false;
			})
			//ajax getting lists of form names exist
			getFormLists(function(){
				var json_p = this;
				var collect_append_option = '<option>--Select--</option>';
			    for (var c in json_p) {
			        collect_append_option
			                += '<option frm-id="' + json_p[c]["wsID"] + '" active-fields="' + json_p[c]["active_fields"] + '" value="' + json_p[c]["wsID"] + '" >' + json_p[c]["form_name"] + '</option>';
			    }
			    self_dialog.find(".mid_rule_sel_formname").html(collect_append_option);
			    self_dialog.find(".getFromsLoader").fadeOut(function(){
			    	$(".mid_rule_sel_formname").fadeIn();
			    	$(this).remove();
			    });
			    self_dialog.find(".mid_rule_sel_formname").children("option").filter(function(){
					if(row_click_data["formname"] == $(this).attr("value")){
						return true;
					}
					return false;
				}).prop("selected",true);

				self_dialog.find(".mid_rule_sel_formname").on("change",function(){
			    	// alert($(this).val())
			    	var dis_self = $(this);
			    	// alert(dis_self.children("option:selected").attr('active-fields'))
			    	var str_active_flds = dis_self.children("option:selected").attr('active-fields');
			    	var spl_active_flds = str_active_flds.split(",");
			    	var collect_active_flds = "";
			    	collect_active_flds += '<option value="TrackNo">TrackNo</option>';
			    	for(var i in spl_active_flds){

			    		collect_active_flds += '<option value="'+spl_active_flds[i]+'">'+spl_active_flds[i]+'</option>';
			    	}
					if($('.workflow-ref-field').length >= 1 ){
						$('.workflow-ref-field').each(function(){
							$(this).html(collect_active_flds);
						});
					}
					if($('.workflow-trigger-fields-filter').length >= 1){
						$('.workflow-trigger-fields-filter').each(function(){
							$(this).html(collect_active_flds);
						});
					}
					if($('.workflow-trigger-fields-update').length >= 1){
						$('.workflow-trigger-fields-update').each(function(){
							$(this).html(collect_active_flds);
						});
					}

					$(".middlewareFormFields").val(spl_active_flds);
			    });
				console.log("asd",arrftrigger)
				if(arrftrigger){
					if(arrftrigger.length != 0){
						if(workflow_actions){
							//viewing
							var json_nodes_var = arrftrigger[0]['value'];
							var workflow_trigger = if_undefinded(json_nodes_var,"");
					        var workflow_trigger2 = if_undefinded(json_nodes_var,"");
					        if(workflow_trigger != ""){
					            var ret = "";
					            for(var i in workflow_trigger){
					                ret += workflow_actions.trigger_html(i,workflow_trigger[i]);

					            }
					            $("#trigger-form").html(ret+'<div style="clear:both;"></div>');

					            ui.unblock()
					            var field_formula = "";
					            for(var i in workflow_trigger){
					                var frm_trigger = $(".trigger-container-fields_"+[i]).find(".workflow-form-trigger");
					                getFormFields(frm_trigger,frm_trigger.val(),"",function(){
					                    if(i==workflow_trigger.length-1){ //perform at the last loop
					                        for(var l in workflow_trigger2){
					                            field_formula = workflow_trigger2[l]['workflow-field_formula'];
					                            for(var kk in field_formula){
					                                // console.log(field_formula[kk])
					                                $("#"+field_formula[kk]['workflow-field-id']).val(field_formula[kk]['workflow-field-update'])
					                            }
					                        }
					                        $(".fields_formula_row").show();
					                        ui.unblock()
					                    }
					                });
					                // $('.workflow-ref-field').children("[value='"+workflow_trigger[i]['workflow-ref-field']+"']").prop("selected",true);
					            }
					            $("#content-dialog-scroll").perfectScrollbar("update");
					        }else{
					        	$(".fields_formula_row").show();
					        }

					        //trigger functions
							workflow_actions.updateTrigger();
							workflow_actions.updateFieldReference();
						}


						self_dialog.find(".mid_rule_sel_formname").trigger("change"); //this must be the last
						for(var i in workflow_trigger){
							console.log()
			               $(".trigger-container-fields_"+i).find(".workflow-ref-field").val(workflow_trigger[i]['workflow-ref-field']);
			               $(".trigger-container-fields_"+i).find(".workflow-trigger-fields-filter").val(workflow_trigger[i]['workflow-trigger-fields-filter']);
			               $(".trigger-container-fields_"+i).find(".workflow-trigger-fields-update").val(workflow_trigger[i]['workflow-trigger-fields-update']);
			               

			            }
					}
				}
				
				//trigger functions
							workflow_actions.updateTrigger();
							workflow_actions.updateFieldReference();
			});

			// console.log(self_row_click.parents("tr").eq(0).data("row_data"));
			
			
			$(this).find(".mid_rule_name").val(row_click_data["rulename"]);
			$(this).find(".mid_rule_description").val(row_click_data["description"])
			
			$(this).find(".mid_rule_formula").val(row_click_data["formula"]);
			$(this).find(".mid_rule_start_date").val(row_click_data["start_formatted"]);
			$(this).find(".mid_rule_end_date").val(row_click_data["end_formatted"]);
			$(this).find(".mid_rule_actions").filter(function(){
				var dis_name = $(this).attr("name");
				for(var index_acts in row_click_data["actions"]){
					// console.log("ACTIONS",row_click_data["actions"]," == ",dis_name)
					if( row_click_data["actions"][index_acts]["name"] == dis_name ){
						return true;
					}
				}

				return false;
			}).prop("checked",true);

			

			
			
			if(arretrigger){
				if(arretrigger.length > 0){
					//restore email
					console.log("EMAIL RESTORATION",arretrigger);
					etrigger_json = arretrigger[0]["value"];
					var email_trig_cont_ele = $("#email-trigger");
					for(var index in etrigger_json){
						if(index == "email-message-type"){
							email_trig_cont_ele.find(".workflow-email-message-type[value='"+etrigger_json[index]+"']").prop("checked",true);
						}else if(index == "email-title-type"){
							email_trig_cont_ele.find(".workflow-email-title-type[value='"+etrigger_json[index]+"']").prop("checked",true);
						}else if(index == "message"){
							email_trig_cont_ele.find("#workflow-email-message").val(etrigger_json["message"])
						}else if(index == "title"){
							email_trig_cont_ele.find("#workflow-email-title").val(etrigger_json["title"]);
						}else {
							var email_bcc_data = etrigger_json[index];
							if(index == "email_bcc"){
								var email_recipients_ele = email_trig_cont_ele.find(".email-bcc");
							}else if(index == "email_cc"){
								var email_recipients_ele = email_trig_cont_ele.find(".email-cc");
							}else if(index == "email_recpient"){
								var email_recipients_ele = email_trig_cont_ele.find(".email-to");
							}else{
								var email_recipients_ele = "";
							}
							if(email_recipients_ele != ""){
								email_recipients_ele.find(".email-requestor").prop("checked",((email_bcc_data["requestor"]==true)?true:false));
								email_recipients_ele.find(".email-processor").prop("checked",((email_bcc_data["processor"]==true)?true:false));
								for(var dep_i in email_bcc_data["departments"]){
									email_bcc_data["departments"][dep_i];
									email_recipients_ele.find(".departments[value='"+email_bcc_data["departments"][dep_i]+"']").prop("checked",true);
								}

								for(var pos_i in email_bcc_data["positions"]){
									email_bcc_data["positions"][pos_i];
									email_recipients_ele.find(".positions[value='"+email_bcc_data["positions"][pos_i]+"']").prop("checked",true);
								}

								for(var users_i in email_bcc_data["users"]){
									email_bcc_data["users"][users_i];
									email_recipients_ele.find(".users[value='"+email_bcc_data["users"][users_i]+"']").prop("checked",true);
								}
							}
						}
					}
				}
			}
			if(arrsmstrigger){
				if(arrsmstrigger.length > 0){
					//restore sms
					console.log("sms RESTORATION",arrsmstrigger);
					smstrigger_json = arrsmstrigger[0]["value"];
					var sms_trig_cont_ele = $("#sms-trigger");
					for(var index in smstrigger_json){
						if(index == "contact"){
							sms_trig_cont_ele.find("#workflow-sms-contact").val(smstrigger_json[index])
						}else if(index == "message"){
							sms_trig_cont_ele.find("#workflow-sms-message").val(smstrigger_json[index])
						}else if(index == "message-type"){
							sms_trig_cont_ele.find(".workflow-sms-message-type[value='"+smstrigger_json[index]+"']").prop("checked",true);
						}else if(index == "processor"){
							sms_trig_cont_ele.find(".sms-processor").prop("checked",smstrigger_json[index]);
						}else if(index == "requestor"){	
							sms_trig_cont_ele.find(".sms-requestor").prop("checked",smstrigger_json[index]);
						}else if(index == "users"){
							for(var sms_users_i in smstrigger_json[index]){
								sms_trig_cont_ele.find(".users[value='"+smstrigger_json[index][sms_users_i]+"']").prop("checked",true);
							}
						}else if(index == "positions"){
							for(var sms_pos_i in smstrigger_json[index]){
								sms_trig_cont_ele.find(".positions[value='"+smstrigger_json[index][sms_pos_i]+"']").prop("checked",true);
							}
						}else if(index == "departments"){
							for(var sms_dept_i in smstrigger_json[index]){
								sms_trig_cont_ele.find(".departments[value='"+smstrigger_json[index][sms_dept_i]+"']").prop("checked",true);
							}
						}
					}
				}
			}

			{
				//restore sched data
				var sched_process_ele = $("#trigger-scheduled-process");
				for(var i_srd in row_click_data['schedule_rep_data']){
					if(row_click_data['schedule_rep_data'][i_srd]["name"] == "schedule_opts"){
						sched_process_ele.find('[name="schedule_opts"][value="'+row_click_data['schedule_rep_data'][i_srd]["value"]+'"]').prop("checked",true);
					
					}else if(row_click_data['schedule_rep_data'][i_srd]["name"] == "mid_rule_date_expire_chk"){
						sched_process_ele.find('[name="mid_rule_date_expire_chk"]').prop("checked",row_click_data['schedule_rep_data'][i_srd]["value"]);
					
					}else if(row_click_data['schedule_rep_data'][i_srd]["name"] == "mid_rule_date_repeatition"){
						sched_process_ele.find('[name="mid_rule_date_repeatition"]').val(row_click_data['schedule_rep_data'][i_srd]["value"]);
					
					}else if(row_click_data['schedule_rep_data'][i_srd]["name"] == "mid_rule_date_repeatition_chk"){
						sched_process_ele.find('[name="mid_rule_date_repeatition_chk"]').prop("checked",row_click_data['schedule_rep_data'][i_srd]["value"]);
					
					}else if(row_click_data['schedule_rep_data'][i_srd]["name"] == "sub-selected-time"){
						for(var i_srd_v in row_click_data['schedule_rep_data'][i_srd]["value"]){
							if(sched_process_ele.find('.sub-selected-time[name="'+i_srd_v+'"]').prop("tagName") == "SELECT"){
								sched_process_ele.find('.sub-selected-time[name="'+i_srd_v+'"]').val(   row_click_data['schedule_rep_data'][i_srd]["value"][i_srd_v]  );
							}else{
								sched_process_ele.find('.sub-selected-time[name="'+i_srd_v+'"]').prop("checked",true);
							}
						}
					}
				}

				$("[name='schedule_opts']").change();

			}
			RequestPivacy.bindOnClickCheckBox();
			RequestPivacy.setCheckAllChecked($(".fp-user-to"));
			RequestPivacy.setCheckAllChecked($(".fp-user-cc"));
			RequestPivacy.setCheckAllChecked($(".fp-user-bcc"));
			RequestPivacy.setCheckAllChecked($(".fp-user-sms"));
			//dito
			//update
			self_dialog.find(".update_rule").on("click",UpdateRule);
		});
	});

































	//REMOVE RULE
	$("body").on("click",".removeRules",function(){
		var self_row_click = $(this).parents("tr").eq(0);
		var self_row_click_data = self_row_click.data("row_data");
		console.log(self_row_click_data)
		$.post("/ajax/middleware_rule_set",{rule_action:"disable_rule","rule_data":JSON.stringify(self_row_click_data)},function(response_data){
			console.log(response_data)
			var res_data = response_data;
			var res_data_json = JSON.parse(res_data);

			if(typeof res_data_json === "object"){
				if(res_data_json["stat"] == "success"){
					if(res_data_json["data_ins"]["is_active"] == "0"){
						self_row_click.find(".data_rule_status").children(".fl-table-ellip").html("Disabled");
						self_row_click.find(".data_rule_actions").find(".removeRules").css("color","red");
						self_row_click.find(".data_rule_actions").find(".enableRules").css("color","");
						
						var store_temp = self_row_click.data();
						if(store_temp["row_data"]){
							if(store_temp["row_data"]["is_active"]){
								store_temp["row_data"]["is_active"] = "0";
							}
						}
						self_row_click.data(store_temp);
						showNotification({
			                message: "Rule has been disabled",
			                type: "",
			                autoClose: true,
			                duration: 3
			            });
					}
				}else{
					showNotification({
		                message: "Error",
		                type: "error",
		                autoClose: true,
		                duration: 3
		            });
				}
			}
			

		});
	});


	$("body").on("click",".enableRules",function(){
		var self_row_click = $(this).parents("tr").eq(0);
		var self_row_click_data = self_row_click.data("row_data");
		console.log(self_row_click_data)
		$.post("/ajax/middleware_rule_set",{rule_action:"enable_rule","rule_data":JSON.stringify(self_row_click_data)},function(response_data){
			
			var res_data = response_data;
			var res_data_json = JSON.parse(res_data);
			console.log("ENABLE",res_data_json)
			if(typeof res_data_json === "object"){
				if(res_data_json["stat"] == "success"){
					if(res_data_json["data_ins"]["is_active"] == "1"){
						self_row_click.find(".data_rule_status").children(".fl-table-ellip").html("Active");
						self_row_click.find(".data_rule_actions").find(".enableRules").css("color","lightgreen");
						self_row_click.find(".data_rule_actions").find(".removeRules").css("color","");
						var store_temp = self_row_click.data();
						if(store_temp["row_data"]){
							if(store_temp["row_data"]["is_active"]){
								store_temp["row_data"]["is_active"] = "0";
							}
						}
						self_row_click.data(store_temp);
						showNotification({
			                message: "Rule has been enabled",
			                type: "",
			                autoClose: true,
			                duration: 3
			            });
					}
				}else{
					showNotification({
		                message: "Error",
		                type: "error",
		                autoClose: true,
		                duration: 3
		            });
				}
			}
			

		});
	});











	//RETRIEVE
	$.post("/ajax/middleware_rule_set",{rule_action:"retrieve"},function(response_data){
		// console.log(response_data);
		// return;
		var json_rd = response_data;
		var json_rd_parse = JSON.parse(response_data);
		if(json_rd_parse){
			if(json_rd_parse.length >= 1){
				$(".no-data-yet").hide();
			}
		}
		//console.log(json_rd_parse);
		var collect_append_datas = "";
		var status_col = "";
		for(var indexKey in json_rd_parse){
			status_col = ((json_rd_parse[indexKey]["is_active"]=="0")?"Disabled":"Active");
			collect_append_datas = ''+
			'<tr>'+
                '<td class="data_rule_name"><div class="fl-table-ellip">'+json_rd_parse[indexKey]["rulename"]+'</div></td>'+
                '<td class="data_rule_descr"><div class="fl-table-ellip">'+json_rd_parse[indexKey]["description"]+'</div></td>'+
                '<td class="data_rule_actions"><div class="fl-table-ellip"><center>'+
                	'<i class="fa fa-edit updateRules" style="cursor:pointer;" data-id="'+json_rd_parse[indexKey]["id"]+'"></i>&nbsp;&nbsp;&nbsp;'+
                	'<i class="fa fa-times removeRules" style="cursor:pointer;'+((status_col=="Disabled")?"color:red;":"")+'" data-id="'+json_rd_parse[indexKey]["id"]+'"></i>&nbsp;&nbsp;&nbsp;'+
                	'<i class="fa fa-check enableRules" style="cursor:pointer;'+((status_col=="Active")?"color:lightgreen;":"")+'" data-id="'+json_rd_parse[indexKey]["id"]+'"></i></center></div></td>'+
                '<td class="data_rule_status"><div class="fl-table-ellip">'+status_col+'</div></td>'+
            '</tr>';
            var jq_collect_append_datas = $(collect_append_datas);
            $(".fl-middleware-table").append(jq_collect_append_datas);
            jq_collect_append_datas.data("row_data",json_rd_parse[indexKey]);
		}
	});
	ui.unblock();
});





























function getFormLists(callBack){
	// $.ajax({
	// 	"url":"/ajax/formbuilder",
	// 	"type":"POST",
	// 	"cache": false,
	// 	"async":false,
	// 	"data":{action: "getFormList"},
	// 	"success":function(dataEchoResults){
	// 		alert(90909)
	// 		var json_p = JSON.parse(dataEchoResults);
	// 	    if(typeof callBack == "function"){
	// 	    	callBack.call(json_p);
	// 	    }
	// 	}
	// });
	if($('.json-data-forms').length >= 1){
		var str_json_data_forms = $('.json-data-forms').html();
		var json_data_forms = JSON.parse(str_json_data_forms);
		if(typeof callBack == "function"){
	    	callBack.call(json_data_forms);
	    }
		// return json_data_forms;
	}
	// $.post("/ajax/formbuilder", {action: "getFormList"}, function(dataEchoResults) {
	    
	// 	// console.log("dataEchoResults",dataEchoResults)
	//     // return;
	//     var json_p = JSON.parse(dataEchoResults);

	//     if(typeof callBack == "function"){
	//     	callBack.call(json_p);
	//     }
	// });
}























function SaveRule(){
	var get_errors = 0;
	var collect_data = [];
	var mid_rule_name = $('.mid_rule_name');
	var mid_rule_description = $('.mid_rule_description');
	var mid_rule_sel_formname = $('.mid_rule_sel_formname');
	var mid_rule_formula = $('.mid_rule_formula');
	var mid_rule_actions = $('.mid_rule_actions');


	//VALIDATION START HERE
	if($('.mid_rule_name').val() == ""){
		NotifyMe($('.mid_rule_name'),"fill this name");
		get_errors++;
	}
	if($('.mid_rule_description').val() == ""){
		NotifyMe($('.mid_rule_description'),"fill this name");
		get_errors++;
	}
	if($('.mid_rule_sel_formname').val() == "--Select--"){
		NotifyMe($('.mid_rule_sel_formname'),"select formname");
		get_errors++;
	}

	if($(".mid_rule_start_date").val() == ""){
		NotifyMe($(".mid_rule_start_date"),"select date start");
		get_errors++;
	}

	if($(".mid_rule_date_expire_chk").prop("checked") == true){
		if($(".mid_rule_end_date").val() == ""){
			NotifyMe($(".mid_rule_end_date"),"select date end");
			get_errors++;
		}
	}
	if(get_errors == 0){
		//COLLECT DATA PUSHES HERE
		{
			collect_data.push({
				"mid_rule_name":mid_rule_name.val(),
				"mid_rule_description":mid_rule_description.val(),
				"mid_rule_sel_formname":mid_rule_sel_formname.val(),
				"mid_rule_formula":mid_rule_formula.val(),
				"mid_rule_date_start":$(".mid_rule_start_date").val(),
				"mid_rule_date_end":$(".mid_rule_end_date").val(),
				"mid_rule_actions":[],
				"mid_rule_sched_data":[]
			});

			{
				//saving field trigger
				var json_nodes_var = [];
				var json_field_trigger = [];
		        $(".trigger-container-fields").each(function(){
		            if($(this).find(".workflow-trigger-action-class:checked").val()=="Create" || $(this).find(".workflow-trigger-action-class:checked").val()=="Update Response"){
		                if($(this).find(".workflow-form-trigger").val()!=0){
		                    var fields_formula = [];
		                    $(this).find(".fields_formula_row").each(function(){
		                        fields_formula.push({
		                            "workflow-field-update" : $(this).find(".workflow-reference-fields-update").val(),
		                            "workflow-field-id" : $(this).find(".workflow-reference-fields-update").attr("id"),
		                            "workflow-field-formula" : $(this).find(".workflow-reference-fields-formula").val(),
		                        })
		                    })
		                    json_field_trigger.push({
		                    	"trigger-index":$(this).attr("trigger-index"),
		                        "workflow-trigger-action":$(this).find(".workflow-trigger-action-class:checked").val(),
		                        "workflow-form-trigger":$(this).find(".workflow-form-trigger").val(),
		                        "workflow-field_formula":fields_formula,
		                        "workflow-ref-field" : $(this).find(".workflow-ref-field").val()
		                    });
		                    json_nodes_var['workflow-trigger'] = json_field_trigger;
		                }
		            }else{
		                json_field_trigger.push({
		                	"trigger-index":$(this).attr("trigger-index"),
		                    "workflow-trigger-action":$(this).find(".workflow-trigger-action-class:checked").val(),
		                    "workflow-trigger-fields-update":$(this).find(".workflow-trigger-fields-update").val(),
		                    "workflow-trigger-fields-filter":$(this).find(".workflow-trigger-fields-filter").val(),
		                    "workflow-trigger-operator":$(this).find(".workflow-trigger-operator").val()
		                });
		                json_nodes_var['workflow-trigger'] = json_field_trigger;
		            }
		        })

				collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":"ftrigger",
					"value":json_field_trigger
				});
			}
			{
				//saving email trigger
				var email_trigger_json = {};

				var workflow_email = {};
                //start to
                var email_to = {};
                var requestor_to = $(".email-to").find(".email-requestor").prop("checked");
                var processor_to = $(".email-to").find(".email-processor").prop("checked");
                var users_to = workflow_actions.setCheckedToJson(".email-to");

                email_to = {
                    "requestor" : requestor_to,
                    "processor" : processor_to,
                };
                email_to = $.extend(users_to,email_to);
                //end to
                //start cc
                var email_cc = {};

                var requestor_cc = $(".email-cc").find(".email-requestor").prop("checked");
                var processor_cc = $(".email-cc").find(".email-processor").prop("checked");
                var users_cc = workflow_actions.setCheckedToJson(".email-cc");

                email_cc = {
                    "requestor" : requestor_cc,
                    "processor" : processor_cc,
                };
                email_cc = $.extend(users_cc,email_cc);

                //end cc

                //start bcc
                var email_bcc = {};

                var requestor_bcc = $(".email-bcc").find(".email-requestor").prop("checked");
                var processor_bcc = $(".email-bcc").find(".email-processor").prop("checked");
                var users_bcc = workflow_actions.setCheckedToJson(".email-bcc");

                email_bcc = {
                    "requestor" : requestor_bcc,
                    "processor" : processor_bcc,
                };
                email_bcc = $.extend(users_bcc,email_bcc);
                //end bcc

                //title and message

                //push to json
                var email_title = $("#workflow-email-title").val();
                var title_type = $(".workflow-email-title-type:checked").val();
                var email_message = $("#workflow-email-message").val();
                var email_message_type = $(".workflow-email-message-type:checked").val();

                workflow_email = {
                    "email_recpient" : email_to,
                    "email_cc"  : email_cc,
                    "email_bcc" : email_bcc,
                    "title"     : email_title,
                    "email-title-type": title_type,
                    "message"   : email_message,
                    "email-message-type" :email_message_type

                };

                // console.log(workflow_email);

                collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":"etrigger",
					"value":workflow_email
				});
			}
			{
				//saving sms trigger
				var workflow_sms = {};
				var requestor_sms = $(".sms-users").find(".sms-requestor").prop("checked");
                var processor_sms = $(".sms-users").find(".sms-processor").prop("checked");
                var users_sms = workflow_actions.setCheckedToJson(".sms-users");
                var sms_contact = $("#workflow-sms-contact").val();
                var sms_message = $("#workflow-sms-message").val();
                var sms_message_type = $(".workflow-sms-message-type:checked").val();
                workflow_sms = {
                    "requestor" : requestor_sms,
                    "processor" : processor_sms,
                    "contact"   : sms_contact,
                    "message"   : sms_message,
                    "message-type" : sms_message_type
                };
                workflow_sms = $.extend(users_sms,workflow_sms);
                console.log("workflow_sms",workflow_sms);

                collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":"smstrigger",
					"value":workflow_sms
				});
			}
			{
				//saving schedule data
				var sched_container = $('#trigger-scheduled-process');
				collect_data[collect_data.length-1];
				var sched_opts = sched_container.find('[name="schedule_opts"]:checked');
				var sched_opts_val = sched_opts.val();
				var cont_sched_acts = "";
				collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"schedule_opts","value":sched_opts.val()});

				if(sched_opts_val == "one_time"){
					cont_sched_acts = sched_container.find(".selected-one-time");
				}else if(sched_opts_val == "more_than_day"){
					cont_sched_acts = sched_container.find(".selected-more-than-day");
				}else if(sched_opts_val == "daily"){
					cont_sched_acts = sched_container.find(".selected-daily");
				}else if(sched_opts_val == "weekly"){
					cont_sched_acts = sched_container.find(".selected-weekly");
				}else if(sched_opts_val == "monthly"){
					cont_sched_acts = sched_container.find(".selected-monthly");
				}

				if(cont_sched_acts.find(".sub-selected-time").length >= 1){
					var collect_sub_selected_time = {};
					cont_sched_acts.find(".sub-selected-time").each(function(){
						var dis_ele = $(this);
						var dis_name = dis_ele.attr("name");
						var dis_val = dis_ele.val();
						if(dis_ele.prop("tagName") == "SELECT"){
							if(typeof collect_sub_selected_time[dis_name] === "undefined"){
								collect_sub_selected_time[dis_name] = dis_val;
							}else{
								collect_sub_selected_time[dis_name] += "|^|"+dis_val;
							}
						}else if(dis_ele.is(":checked")){
							if(typeof collect_sub_selected_time[dis_name] === "undefined"){
								collect_sub_selected_time[dis_name] = dis_val;
							}else{
								collect_sub_selected_time[dis_name] += "|^|"+dis_val;
							}
						}
					});
					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"sub-selected-time","value":collect_sub_selected_time});

					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"mid_rule_date_expire_chk","value":$('[name="mid_rule_date_expire_chk"]').prop("checked")});
					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"mid_rule_date_repeatition","value":$('[name="mid_rule_date_repeatition"]').val()});
					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"mid_rule_date_repeatition_chk","value":$('[name="mid_rule_date_repeatition_chk"]').prop("checked")});
					
				}
			}
			
		}
		console.log(collect_data);
		var cd_json_str = JSON.stringify(collect_data);

		$.post("/ajax/middleware_rule_set",{rule_action:"save",rule_data:cd_json_str},function(response_data){
			console.log(response_data);
			var rd = response_data;
			var json_p_rd = JSON.parse(rd);
			if(json_p_rd["stat"] == "success"){
				var collect_append_datas = "";
				status_col = "Active";
				collect_append_datas += ''+
				'<tr>'+
	                '<td class="data_rule_name"><div class="fl-table-ellip">'+json_p_rd["data_ins"]["rulename"]+'</div></td>'+
	                '<td class="data_rule_descr"><div class="fl-table-ellip">'+json_p_rd["data_ins"]["description"]+'</div></td>'+
	                //'<td class="data_rule_actions"><div class="fl-table-ellip"><center><i class="fa fa-edit updateRules" style="cursor:pointer;" data-id="'+json_p_rd["data_ins"]["id"]+'"></i>&nbsp;&nbsp;&nbsp;<i class="fa fa-times removeRules" style="cursor:pointer;" data-id="'+json_p_rd["data_ins"]["id"]+'"></i></center></div></td>'+
	                '<td class="data_rule_actions"><div class="fl-table-ellip"><center>'+
	                	'<i class="fa fa-edit updateRules" style="cursor:pointer;" data-id="'+json_p_rd["data_ins"]["id"]+'"></i>&nbsp;&nbsp;&nbsp;'+
	                	'<i class="fa fa-times removeRules" style="cursor:pointer;'+((status_col=="Disabled")?"color:red;":"")+'" data-id="'+json_p_rd["data_ins"]["id"]+'"></i>&nbsp;&nbsp;&nbsp;'+
	                	'<i class="fa fa-check enableRules" style="cursor:pointer;'+((status_col=="Active")?"color:lightgreen;":"")+'" data-id="'+json_p_rd["data_ins"]["id"]+'"></i></center></div>'+
                	'</td>'+
	                '<td class="data_rule_status"><div class="fl-table-ellip">Active</div></td>'+
	            '</tr>';
	            var jq_collect_append_datas = $(collect_append_datas);
	            $(".fl-middleware-table").append(jq_collect_append_datas);
	            jq_collect_append_datas.data("row_data",json_p_rd["data_ins"]);
	            $(".no-data-yet").hide();
	            $(".fl-closeDialog").trigger("click");
	            showNotification({
	                message: "Rules added and successfully saved.",
	                type: "",
	                autoClose: true,
	                duration: 3
	            });
			}else{
				showNotification({
	                message: "Error data not saved",
	                type: "error",
	                autoClose: true,
	                duration: 3
	            });
			}
		});
	}
}





































function UpdateRule(){
	var data_clicked = $("#popup_container").data("data_clicked");
	var row_selector = $("#popup_container").data("row_selector");
	var get_errors = 0;
	var collect_data = [];
	var mid_rule_name = $('.mid_rule_name');
	var mid_rule_description = $('.mid_rule_description');
	var mid_rule_sel_formname = $('.mid_rule_sel_formname');
	var mid_rule_formula = $('.mid_rule_formula');
	var mid_rule_actions = $('.mid_rule_actions');
	var mid_rule_date_exe = $('.mid_rule_date_exe');
	
	if($('.mid_rule_name').val() == ""){
		NotifyMe($('.mid_rule_name'),"fill this name");
		get_errors++;
	}
	if($('.mid_rule_description').val() == ""){
		NotifyMe($('.mid_rule_description'),"fill this name");
		get_errors++;
	}
	if($('.mid_rule_sel_formname').val() == "--Select--"){
		NotifyMe($('.mid_rule_sel_formname'),"select formname");
		get_errors++;
	}
	var mid_rule_date_exe_selector = $(".mid_rule_date_exe").filter(function(){if($(this).val() != ""){ return true; }else{ return false; } });
	if(mid_rule_date_exe_selector.length == 0){
		get_errors++;
	}
	if($(".mid_rule_start_date").val() == ""){
		NotifyMe($(".mid_rule_start_date"),"select date start");
	}
	if($(".mid_rule_date_expire_chk").prop("checked") == true){
		if($(".mid_rule_end_date").val() == ""){
			NotifyMe($(".mid_rule_end_date"),"select date end");
		}
	}

	if(get_errors == 0){
		
		//COLLECT DATA PUSHES HERE
		{
			collect_data.push({
				"id":data_clicked["id"],
				"mid_rule_name":mid_rule_name.val(),
				"mid_rule_description":mid_rule_description.val(),
				"mid_rule_sel_formname":mid_rule_sel_formname.val(),
				"mid_rule_formula":mid_rule_formula.val(),
				"mid_rule_date_start":mid_rule_date_exe.filter(".mid_rule_start_date").val(),
				"mid_rule_date_end":mid_rule_date_exe.filter(".mid_rule_end_date").val(),
				"mid_rule_actions":[],
				"mid_rule_sched_data":[]
			});

			$(mid_rule_actions).filter(":checked").each(function(){
				var self_c = $(this);
				var self_name = self_c.attr("name");
				var self_value = self_c.val();
				collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":self_name,
					"value":self_value
				});
			});

			{
				//saving field trigger
				var json_nodes_var = [];
				var json_field_trigger = [];
		        $(".trigger-container-fields").each(function(){
		            if($(this).find(".workflow-trigger-action-class:checked").val()=="Create" || $(this).find(".workflow-trigger-action-class:checked").val()=="Update Response"){
		                if($(this).find(".workflow-form-trigger").val()!=0){
		                    var fields_formula = [];
		                    $(this).find(".fields_formula_row").each(function(){
		                        fields_formula.push({
		                            "workflow-field-update" : $(this).find(".workflow-reference-fields-update").val(),
		                            "workflow-field-id" : $(this).find(".workflow-reference-fields-update").attr("id"),
		                            "workflow-field-formula" : $(this).find(".workflow-reference-fields-formula").val(),
		                        })
		                    })
		                    json_field_trigger.push({
		                    	"trigger-index":$(this).attr("trigger-index"),
		                        "workflow-trigger-action":$(this).find(".workflow-trigger-action-class:checked").val(),
		                        "workflow-form-trigger":$(this).find(".workflow-form-trigger").val(),
		                        "workflow-field_formula":fields_formula,
		                        "workflow-ref-field" : $(this).find(".workflow-ref-field").val()
		                    });
		                    json_nodes_var['workflow-trigger'] = json_field_trigger;
		                }
		            }else{
		                json_field_trigger.push({
		                	"trigger-index":$(this).attr("trigger-index"),
		                    "workflow-trigger-action":$(this).find(".workflow-trigger-action-class:checked").val(),
		                    "workflow-trigger-fields-update":$(this).find(".workflow-trigger-fields-update").val(),
		                    "workflow-trigger-fields-filter":$(this).find(".workflow-trigger-fields-filter").val(),
		                    "workflow-trigger-operator":$(this).find(".workflow-trigger-operator").val()
		                });
		                json_nodes_var['workflow-trigger'] = json_field_trigger;
		            }
		        })

				collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":"ftrigger",
					"value":json_field_trigger
				});
			}
			{
				//saving email trigger
				var email_trigger_json = {};

				var workflow_email = {};
                //start to
                var email_to = {};
                var requestor_to = $(".email-to").find(".email-requestor").prop("checked");
                var processor_to = $(".email-to").find(".email-processor").prop("checked");
                var users_to = workflow_actions.setCheckedToJson(".email-to");

                email_to = {
                    "requestor" : requestor_to,
                    "processor" : processor_to,
                };
                email_to = $.extend(users_to,email_to);
                //end to
                //start cc
                var email_cc = {};

                var requestor_cc = $(".email-cc").find(".email-requestor").prop("checked");
                var processor_cc = $(".email-cc").find(".email-processor").prop("checked");
                var users_cc = workflow_actions.setCheckedToJson(".email-cc");

                email_cc = {
                    "requestor" : requestor_cc,
                    "processor" : processor_cc,
                };
                email_cc = $.extend(users_cc,email_cc);

                //end cc

                //start bcc
                var email_bcc = {};

                var requestor_bcc = $(".email-bcc").find(".email-requestor").prop("checked");
                var processor_bcc = $(".email-bcc").find(".email-processor").prop("checked");
                var users_bcc = workflow_actions.setCheckedToJson(".email-bcc");

                email_bcc = {
                    "requestor" : requestor_bcc,
                    "processor" : processor_bcc,
                };
                email_bcc = $.extend(users_bcc,email_bcc);
                //end bcc

                //title and message

                //push to json
                var email_title = $("#workflow-email-title").val();
                var title_type = $(".workflow-email-title-type:checked").val();
                var email_message = $("#workflow-email-message").val();
                var email_message_type = $(".workflow-email-message-type:checked").val();

                workflow_email = {
                    "email_recpient" : email_to,
                    "email_cc"  : email_cc,
                    "email_bcc" : email_bcc,
                    "title"     : email_title,
                    "email-title-type": title_type,
                    "message"   : email_message,
                    "email-message-type" :email_message_type

                };

                console.log(workflow_email);

                collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":"etrigger",
					"value":workflow_email
				});
			}

			{
				//saving sms trigger
				var workflow_sms = {};
				var requestor_sms = $(".sms-users").find(".sms-requestor").prop("checked");
                var processor_sms = $(".sms-users").find(".sms-processor").prop("checked");
                var users_sms = workflow_actions.setCheckedToJson(".sms-users");
                var sms_contact = $("#workflow-sms-contact").val();
                var sms_message = $("#workflow-sms-message").val();
                var sms_message_type = $(".workflow-sms-message-type:checked").val();
                workflow_sms = {
                    "requestor" : requestor_sms,
                    "processor" : processor_sms,
                    "contact"   : sms_contact,
                    "message"   : sms_message,
                    "message-type" : sms_message_type
                };
                workflow_sms = $.extend(users_sms,workflow_sms);
                console.log("workflow_sms",workflow_sms);

                collect_data[collect_data.length-1]["mid_rule_actions"].push({
					"name":"smstrigger",
					"value":workflow_sms
				});
			}

			{
				//saving schedule data
				var sched_container = $('#trigger-scheduled-process');
				collect_data[collect_data.length-1];
				var sched_opts = sched_container.find('[name="schedule_opts"]:checked');
				var sched_opts_val = sched_opts.val();
				var cont_sched_acts = "";
				collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"schedule_opts","value":sched_opts.val()});

				if(sched_opts_val == "one_time"){
					cont_sched_acts = sched_container.find(".selected-one-time");
				}else if(sched_opts_val == "more_than_day"){
					cont_sched_acts = sched_container.find(".selected-more-than-day");
				}else if(sched_opts_val == "daily"){
					cont_sched_acts = sched_container.find(".selected-daily");
				}else if(sched_opts_val == "weekly"){
					cont_sched_acts = sched_container.find(".selected-weekly");
				}else if(sched_opts_val == "monthly"){
					cont_sched_acts = sched_container.find(".selected-monthly");
				}

				if(cont_sched_acts.find(".sub-selected-time").length >= 1){
					var collect_sub_selected_time = {};
					cont_sched_acts.find(".sub-selected-time").each(function(){
						var dis_ele = $(this);
						var dis_name = dis_ele.attr("name");
						var dis_val = dis_ele.val();
						if(dis_ele.prop("tagName") == "SELECT"){
							if(typeof collect_sub_selected_time[dis_name] === "undefined"){
								collect_sub_selected_time[dis_name] = dis_val;
							}else{
								collect_sub_selected_time[dis_name] += "|^|"+dis_val;
							}
						}else if(dis_ele.is(":checked")){
							if(typeof collect_sub_selected_time[dis_name] === "undefined"){
								collect_sub_selected_time[dis_name] = dis_val;
							}else{
								collect_sub_selected_time[dis_name] += "|^|"+dis_val;
							}
						}
					});
					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"sub-selected-time","value":collect_sub_selected_time});

					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"mid_rule_date_expire_chk","value":$('[name="mid_rule_date_expire_chk"]').prop("checked")});
					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"mid_rule_date_repeatition","value":$('[name="mid_rule_date_repeatition"]').val()});
					collect_data[collect_data.length-1]["mid_rule_sched_data"].push({"name":"mid_rule_date_repeatition_chk","value":$('[name="mid_rule_date_repeatition_chk"]').prop("checked")});
					
				}
			}
		}

		var cd_json_str = JSON.stringify(collect_data);
		console.log(cd_json_str)
		$.post("/ajax/middleware_rule_set",{rule_action:"update",rule_data:cd_json_str},function(response_data){
			// console.log(response_data);
			var rd = response_data;
			var json_p_rd = JSON.parse(rd);
			if(json_p_rd["stat"] == "success"){

	            var row_select = row_selector;
	            // console.log("BADTRIP",json_p_rd,$(row_select).children(".data_rule_name:eq(0)").children(".fl-table-ellip:eq(0)"),json_p_rd["data_ins"]["rulename"])
	            $(row_select).children(".data_rule_name:eq(0)").children(".fl-table-ellip:eq(0)").html(json_p_rd["data_ins"]["rulename"]);
	            $(row_select).children(".data_rule_descr:eq(0)").children(".fl-table-ellip:eq(0)").html(json_p_rd["data_ins"]["description"]);
				console.log("FATIGUE", $(row_select).children(".data_rule_descr:eq(0)").children(".fl-table-ellip:eq(0)"))
				var RD = $(row_select).data("row_data");
				RD = $.extend(RD,json_p_rd["data_ins"]);
				console.log("RD",RD);
	            
	            $(".no-data-yet").hide();
	            $(".fl-closeDialog").trigger("click");
	            showNotification({
	                message: "Rules added and successfully saved.",
	                type: "",
	                autoClose: true,
	                duration: 3
	            });
			}else{
				showNotification({
	                message: "Error data not saved",
	                type: "error",
	                autoClose: true,
	                duration: 3
	            });
			}
		});
	}else{

	}
}




































function RuleDialog(opts,cB){
	var date_months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
	var date_days = [];
	for(var i = 1; i <= 31; i++) {
	    date_days.push((i));
	};
	console.log("date_days",date_days)
	
	var ret = 
	'<h3 class="fl-margin-bottom"><i class="icon-save"></i>New Rule Properties</h3>'+
	'<div class="middleware-settings-dialog content-dialog-scroll" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; overflow: hidden;" class="ps-container">'+
		'<div class="content-dialog" style="height: auto;">'+
			'<div class="hr"></div>'+
			'<form>'+
				'<div class="fields">'+
					'<div class="label_below2"> Rule Name:<font color="red">*</font> </div>'+
					'<div class="input_position">'+
						'<input type="text" name="middleware_rule_name" id="middleware_rule_name" class="mid_rule_name form-text fl-margin-bottom" style="margin-top:5px;" value="" />'+
					'</div>'+
				'</div>'+
				'<div class="fields">'+
					'<div class="label_below2"> Description:<font color="red">*</font> </div>'+
					'<div class="input_position">'+
						'<input type="text" name="middleware_rule_description" id="middleware_rule_description" class="mid_rule_description form-text fl-margin-bottom" style="margin-top:5px;" value="" />'+
					'</div>'+
				'</div>'+
				'<div class="fields">'+
					'<div class="label_below2"> Form Name:<font color="red">*</font> </div>'+
					'<div class="input_position">'+
						'<div class="getFromsLoader form-select" style="display:inline-block;position:relative;vertical-align:middle;text-align:center;"><label style="color:black;position:reltive;font-size: 15px;display:inline-block;">Loading...</label><img src="/images/loader/loader.gif" class="display processorLoad" style="display: inline-block;"/></div>'+
						'<select class="mid_rule_sel_formname form-select" style="display:none;width:100%;">'+
							'<option>--SELECT FORM--</option>'+
						'</select>'+
					'</div>'+
				'</div>'+

				'<div class="fields">'+
					'<div class="label_below2"> Record Selection:<font color="red"></font> </div>'+
					'<div class="input_position">'+
						'<textarea class="mid_rule_formula form-textarea"></textarea>'+
					'</div>'+
				'</div>'+

				


				'<div class="fields action-advance-settings">'+
					'<div class="label_below2"> Advance Settings:</div>'+
					'<div id="action-advance-settings-tabs">'+
						'<ul>'+
							'<li><a href="#trigger-scheduled-process">Schedule Process</a></li>'+
							'<li><a href="#trigger-form">Triggers forms</a></li>'+
							'<li><a href="#email-trigger">Email</a></li>'+
							'<li><a href="#sms-trigger">SMS</a></li>'+
						'</ul>'+









						'<div id="trigger-scheduled-process" style="position: relative; overflow: hidden;">'+
							'<div class="fields fl-margin-bottom">'+
								'<div class="label_below2"> Actions:<font color="red">*</font> </div>'+
								'<div class="input_position">'+
									'<label class="fl-margin-right"><input class="mid_rule_actions css-checkbox" name="schedule_opts" type="radio" value="one_time" checked="checked" id="one_time"/><label for="one_time" class="css-label"></label> One time</label>'+
									// '<label><input class="mid_rule_actions" name="schedule_opts" type="radio" value="more_than_day"/> More than a day</label><br/>'+
									'<label class="fl-margin-right"><input class="mid_rule_actions css-checkbox" name="schedule_opts" type="radio" value="daily" id="daily"/><label for="daily" class="css-label"></label> Daily</label>'+
									'<label class="fl-margin-right"><input class="mid_rule_actions css-checkbox" name="schedule_opts" type="radio" value="weekly" id="weekly"/><label for="weekly" class="css-label"></label> Weekly</label>'+
									'<label><input class="mid_rule_actions css-checkbox" name="schedule_opts" type="radio" value="monthly" id="monthly"/><label for="monthly" class="css-label"></label> Monthly</label>'+
								'</div>'+
							'</div>'+
							'<div class="fields" style="margin-bottom:10px; width:98%;display:inline-block;min-height: 65px; padding:10px; background-color:#f4f4f4;">'+
								'<div class="input_position">'+
									'<div class="container-selected-opts selected-one-time">'+
										// '<h1>ONE TIME</h1>'+
									'</div>'+
									'<div class="container-selected-opts selected-more-than-day" style="display:none">'+
										// '<h1>MORE THAN A DAY</h1>'+
									'</div>'+
									'<div class="container-selected-opts selected-daily" style="display:none">'+
										'<label><input name="selected_daily_weekend" class="sub-selected-time selected_daily selected_daily_weekend css-checkbox" type="checkbox" placeholder="Weekends" style="background:#FFF;border: 1px solid #D5D5D5;padding: 7px;font-size: 11px;box-sizing:border-box; border-radius:4px; " id="selected_daily_weekend"/><label for="selected_daily_weekend" class="css-label"></label> Weekend</label>'+
									'</div>'+
									'<div class="container-selected-opts selected-weekly" style="display:none">'+
										// '<h1>WEEKLY</h1>'+
										'<label>Select day: <select name="selected_weekly_byday" class="sub-selected-time selected_weekly selected_weekly_byday">'+
											'<option value="monday">Monday</option>'+
											'<option value="tuesday">Tuesday</option>'+
											'<option value="wednesday">Wednesday</option>'+
											'<option value="thursday">Thursday</option>'+
											'<option value="friday">Friday</option>'+
											'<option value="saturday">Saturday</option>'+
											'<option value="sunday">Sunday</option>'+
										'</select></label>'+
									'</div>'+
									'<div class="container-selected-opts selected-monthly" style="display:none">'+
										'<div class="fields" style="">'+
											'<div class="label_below2"><h4> Months:</h4></div>'+
											'<div class="input_position">'+
												'<div style="">';
													for(var i_m in date_months){
														if ((i_m+1) %4 == 0) {
															ret += '<label class="fl-margin-right" style="margin-bottom:5px; display:inline-block;"><input type="checkbox" name="monthly_months_'+date_months[i_m]+'" class="css-checkbox sub-selected-time monthly_months monthly_months_'+date_months[i_m]+'" value="'+(Number(i_m)+1)+'" id="monthly_months_'+date_months[i_m]+'" /><label for="monthly_months_'+date_months[i_m]+'" class="css-label"></label> <span>'+date_months[i_m]+'</span></label><br/>';
														}else{
															ret += '<label class="fl-margin-right" style="margin-bottom:5px; display:inline-block;"><input type="checkbox" name="monthly_months_'+date_months[i_m]+'" class="css-checkbox sub-selected-time monthly_months monthly_months_'+date_months[i_m]+'" value="'+(Number(i_m)+1)+'" id="monthly_months_'+date_months[i_m]+'" /><label for="monthly_months_'+date_months[i_m]+'" class="css-label"></label> <span>'+date_months[i_m]+'</span></label>';
														};
														
													}
												ret += '</div>'+
											'</div>'+
										'</div>'+
										'<hr/>'+
										'<div class="fields dasd">'+
											'<div class="label_below2"><h4> Days:</h4></div>'+
											'<div class="input_position">'+
												'<div style="">';
													for(var i_d in date_days){
														ret += '<label class="fl-margin-right" style="margin-bottom:5px; display:inline-block;"><input type="checkbox" name="monthly_days_'+date_days[i_d]+'" class="css-checkbox sub-selected-time monthly_days monthly_days_'+date_days[i_d]+'" value="'+date_days[i_d]+'" id="monthly_days_'+date_days[i_d]+'" /><label for="monthly_days_'+date_days[i_d]+'" class="css-label"></label> <span>'+date_days[i_d]+'</span></label>';
													}
												ret += '</div>'+
											'</div>'+
										'</div>'+

										'<div style="clear:both;"></div>'+
									'</div>'+
								'</div>'+
							'</div>'+

							'<div class="fields" style="width:25%;display:inline-block">'+
								'<div class="label_below2" style="float:left"> Start Time:</div>'+
								'<div class="input_position">'+
									'<input name="mid_rule_date_start" class="mid_rule_date_exe mid_rule_start_date" type="text" placeholder="Start date" style="background:#FFF;border: 1px solid #D5D5D5;padding: 7px;font-size: 11px;box-sizing:border-box; border-radius:4px;"/>'+
									
								'</div>'+
								'<div style="clear:both;"></div>'+
							'</div>'+
							'<div class="fields" style="width:30%;display:inline-block">'+
								'<div class="label_below2" style="float:left"><label><input name="mid_rule_date_expire_chk" class="css-checkbox mid_rule_date_chk mid_rule_date_expire_chk" type="checkbox" placeholder="Enable Expire" style="background:#FFF;border: 1px solid #D5D5D5;padding: 7px;font-size: 11px;box-sizing:border-box; border-radius:4px; " checked="checked" id="mid_rule_date_expire_chk"/><label for="mid_rule_date_expire_chk" class="css-label"></label> Expire Time:</label></div>'+
								'<div class="input_position">'+

									'<input name="mid_rule_date_end" class="mid_rule_date_exe mid_rule_end_date" type="text" placeholder="End date" style="background:#FFF;border: 1px solid #D5D5D5;padding: 7px;font-size: 11px;box-sizing:border-box; border-radius:4px; "/>'+
								'</div>'+
								'<div style="clear:both;"></div>'+
							'</div>'+

							'<div class="fields">'+
								'<div class="label_below2" style="float:left"><input name="mid_rule_date_repeatition_chk" class="css-checkbox mid_rule_date_chk mid_rule_date_repeatition_chk" type="checkbox" placeholder="Enable Expire" style="background:#FFF;border: 1px solid #D5D5D5;padding: 7px;font-size: 11px;box-sizing:border-box; border-radius:4px; " checked="checked" id="mid_rule_date_repeatition_chk"/><label for="mid_rule_date_repeatition_chk" class="css-label"></label> Repeat process every: </div>'+
								'<div style="clear:both;"></div>'+
								'<div class="input_position">'+
									// '<input name="mid_rule_date_repeatition" class="mid_rule_date_exe mid_rule_date_repeatition" type="text" placeholder="Repeatition" style="background:#FFF;border: 1px solid #D5D5D5;padding: 7px;font-size: 11px;box-sizing:border-box; border-radius:4px;"/>'+
									'<select name="mid_rule_date_repeatition" class="mid_rule_date_exe mid_rule_date_repeatition">'+
										'<option value="5min">5 minutes</option>'+
										'<option value="10min">10 minutes</option>'+
										'<option value="15min">15 minutes</option>'+
										'<option value="30min">30 minutes</option>'+
										'<option value="1hr">1 hour</option>'+
									'</select>'+
								'</div>'+
							'</div>'+

							


							'<div style="clear:both;"></div>'+
						'</div>'+











						'<div id="trigger-form" style="position: relative; overflow: hidden;">'+
							// '<h1>TRIGGER OTHER FORMS</h1>'+
							workflow_actions.trigger_html(0,"")+
							'<div style="clear:both;"></div>'+
						'</div>'+





































						'<div id="email-trigger">';
							// '<h1>EMAIL TRIGGER</h1>'+
							{
								ret += '<div id="accordion">'+
									    '<label>To:</label>'+
									    '<div class="fp-container email-to">'+
									        '<div style="width:100%;display:inline-block">'+
									            '<div style="width:30%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="email-requestor css-checkbox" value="All Users" id="email-requestor-TO"><label for="email-requestor-TO" class="css-label"></label> Requestor</label>'+
									            '</div>'+
									            '<div style="width:50%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="email-processor css-checkbox" value="All Users" id="email-processor-TO"><label for="email-processor-TO" class="css-label"></label> Next Processor</label>'+
									            '</div>'+
									        '</div>'+
									        '<label>'+
									            '<input type="checkbox" class="fp-allUsers css-checkbox" value="All Users" id="fp-allUsers-TO"><label for="fp-allUsers-TO" class="css-label"></label> All Users</label>'+
									        '<br>'+
									        '<div class="content-dialog-scroll2" style="position: relative; margin-left: 20px; padding: 0px; width: 100%; height: 240px;overflow: hidden;">'+
									            '<div>'+
									                '<div class="content-dialog2" style="width: 90%;height: auto;">'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getDepartmentFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Department</label>'+
									                        '</div>'+
									                        '<div class="getDepartmentFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                        	var departments = $(".departments").text();
						                                        var ctr_dept = 0;
						                                        if(departments){
						                                            departments = JSON.parse(departments);
						                                            $.each(departments,function(key, val){
						                                                ret += '<div style="width:30%;float:left;"> ';
						                                                //setCheckedArray(value, arr)
						                                                    ret += '<label class="tip" title="' + val.department + '"><input type="checkbox" class="fp-user fp-user-to departments css-checkbox" value="'+ val.id +'" id="fp-user-TO_dept_'+ val.id +'"/><label for="fp-user-TO_dept_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.department +'</span></label>';
						                                                ret += '</div>';
						                                                ctr_dept++
						                                            })
						                                        }
						                                        if(ctr_dept==0){
						                                            ret += '<span style="color:red">No Department</span>';
						                                        }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getPositionFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Position</label>'+
									                        '</div>'+
									                        '<div class="getPositionFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var positions = $(".positions").text();
					                                            var ctr_pos = 0;
					                                            if(positions){
					                                                positions = JSON.parse(positions);

					                                                $.each(positions,function(key, val){
					                                                    if(val.position !=""){
					                                                        ret += '<div style="width:30%;float:left;"> ';
					                                                            ret += '<label class="tip" title="' + val.position + '"><input type="checkbox" class="fp-user fp-user-to positions css-checkbox" value="'+ val.position +'" id="fp-user-TO_POSITIONS_'+ val.position +'"/><label for="fp-user-TO_POSITIONS_'+ val.position +'" class="css-label"></label> <span class="limit-text-wf">'+ val.position +'</span></label>';
					                                                        ret += '</div>';
					                                                        ctr_pos++;
					                                                    }
					                                                })
					                                                
					                                            }
					                                            if(ctr_pos==0){
					                                                ret += '<span style="color:red">No Positions</span>';
					                                            }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getUsersFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Users</label>'+
									                        '</div>'+
									                        '<div class="getUsersFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var users = $(".users").text();
				                                                if(users){
				                                                    users = JSON.parse(users);
				                                                    $.each(users,function(key, val){
				                                                        ret += '<div style="width:30%;float:left; margin-bottom:2px;"> ';
				                                                            ret += '<label class="tip" title="'+ val.first_name +' '+ val.last_name +'"><input type="checkbox" class="fp-user fp-user-to users css-checkbox" value="'+ val.id +'" id="fp-user-to_users_'+ val.id +'"/><label for="fp-user-to_users_'+ val.id +'"class="css-label"></label> <span class="limit-text-wf">'+ val.first_name +' '+ val.last_name +'</span></label>';
				                                                        ret += '</div>';
				                                                    })
				                                                }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="clearfix"></div>'+
									                '</div>'+
									            '</div>'+
									        '</div>'+
									    '</div>'+
									    '<label>CC:</label>'+
									    '<div class="fp-container email-cc">'+
									        '<div style="width:100%;display:inline-block">'+
									            '<div style="width:30%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="email-requestor css-checkbox" value="All Users" id="email-requestor-CC"><label for="email-requestor-CC" class="css-label"></label> Requestor</label>'+
									            '</div>'+
									            '<div style="width:50%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="email-processor css-checkbox" value="All Users" id="email-processor-CC"><label for="email-processor-CC" class="css-label"></label> Next Processor</label>'+
									            '</div>'+
									        '</div>'+
									        '<label>'+
									            '<input type="checkbox" class="fp-allUsers css-checkbox" value="All Users" id="fp-allUsers-CC"><label for="fp-allUsers-CC" class="css-label"></label> All Users</label>'+
									        '<br>'+
									        '<div class="content-dialog-scroll2" style="position: relative; margin-left: 20px; padding: 0px; width: 100%; height: 240px;overflow: hidden;">'+
									            '<div>'+
									                '<div class="content-dialog2" style="width: 90%;height: auto;">'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getDepartmentFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Department</label>'+
									                        '</div>'+
									                        '<div class="getDepartmentFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                        	var departments = $(".departments").text();
						                                        var ctr_dept = 0;
						                                        if(departments){
						                                            departments = JSON.parse(departments);
						                                            $.each(departments,function(key, val){
						                                                ret += '<div style="width:30%;float:left;"> ';
						                                                //setCheckedArray(value, arr)
						                                                    ret += '<label class="tip" title="' + val.department + '"><input type="checkbox" class="fp-user fp-user-cc departments css-checkbox" value="'+ val.id +'" id="fp-user-CC_dept_'+ val.id +'"/><label for="fp-user-CC_dept_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.department +'</span></label>';
						                                                ret += '</div>';
						                                                ctr_dept++
						                                            })
						                                        }
						                                        if(ctr_dept==0){
						                                            ret += '<span style="color:red">No Department</span>';
						                                        }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getPositionFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Position</label>'+
									                        '</div>'+
									                        '<div class="getPositionFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var positions = $(".positions").text();
					                                            var ctr_pos = 0;
					                                            if(positions){
					                                                positions = JSON.parse(positions);

					                                                $.each(positions,function(key, val){
					                                                    if(val.position !=""){
					                                                        ret += '<div style="width:30%;float:left;"> ';
					                                                            ret += '<label class="tip" title="' + val.position + '"><input type="checkbox" class="fp-user fp-user-cc positions css-checkbox" value="'+ val.position +'" id="fp-user-CC_POSITIONS_'+ val.position +'"/><label for="fp-user-CC_POSITIONS_'+ val.position +'" class="css-label"></label> <span class="limit-text-wf">'+ val.position +'</span></label>';
					                                                        ret += '</div>';
					                                                        ctr_pos++;
					                                                    }
					                                                })
					                                                
					                                            }
					                                            if(ctr_pos==0){
					                                                ret += '<span style="color:red">No Positions</span>';
					                                            }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getUsersFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Users</label>'+
									                        '</div>'+
									                        '<div class="getUsersFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var users = $(".users").text();
				                                                if(users){
				                                                    users = JSON.parse(users);
				                                                    $.each(users,function(key, val){
				                                                        ret += '<div style="width:30%;float:left;margin-bottom:2px;"> ';
				                                                            ret += '<label class="tip" title="'+ val.first_name +' '+ val.last_name +'"><input type="checkbox" class="fp-user fp-user-cc users css-checkbox" value="'+ val.id +'" id="fp-user-cc_users_'+ val.id +'"/><label for="fp-user-cc_users_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.first_name +' '+ val.last_name +'</span></label>';
				                                                        ret += '</div>';
				                                                    })
				                                                }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="clearfix"></div>'+
									                '</div>'+
									            '</div>'+
									        '</div>'+
									    '</div>'+
									    '<label>BCC:</label>'+
									    '<div class="fp-container email-bcc">'+
									        '<div style="width:100%;display:inline-block">'+
									            '<div style="width:30%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="email-requestor css-checkbox" value="All Users" id="email-requestor-BCC"><label for="email-requestor-BCC" class="css-label"></label> Requestor</label>'+
									            '</div>'+
									            '<div style="width:50%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="email-processor css-checkbox" value="All Users" id="email-processor-BCC"><label for="email-processor-BCC" class="css-label"></label> Next Processor</label>'+
									            '</div>'+
									        '</div>'+
									        '<label>'+
									            '<input type="checkbox" class="fp-allUsers css-checkbox" value="All Users" id="fp-allUsers-BCC"><label for="fp-allUsers-BCC" class="css-label"></label> All Users</label>'+
									        '<br>'+
									        '<div class="content-dialog-scroll2" style="position: relative; margin-left: 20px; padding: 0px; width: 100%; height: 240px;overflow: hidden;">'+
									            '<div>'+
									                '<div class="content-dialog2" style="width: 90%;height: auto;">'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getDepartmentFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Department</label>'+
									                        '</div>'+
									                        '<div class="getDepartmentFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                        	var departments = $(".departments").text();
						                                        var ctr_dept = 0;
						                                        if(departments){
						                                            departments = JSON.parse(departments);
						                                            $.each(departments,function(key, val){
						                                                ret += '<div style="width:30%;float:left;"> ';
						                                                //setCheckedArray(value, arr)
						                                                    ret += '<label class="tip" title="' + val.department + '"><input type="checkbox" class="fp-user fp-user-bcc departments css-checkbox" value="'+ val.id +'" id="fp-user-BCC_dept_'+ val.id +'"/><label for="fp-user-BCC_dept_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.department +'</span></label>';
						                                                ret += '</div>';
						                                                ctr_dept++
						                                            })
						                                        }
						                                        if(ctr_dept==0){
						                                            ret += '<span style="color:red">No Department</span>';
						                                        }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getPositionFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Position</label>'+
									                        '</div>'+
									                        '<div class="getPositionFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var positions = $(".positions").text();
					                                            var ctr_pos = 0;
					                                            if(positions){
					                                                positions = JSON.parse(positions);

					                                                $.each(positions,function(key, val){
					                                                    if(val.position !=""){
					                                                        ret += '<div style="width:30%;float:left;"> ';
					                                                            ret += '<label class="tip" title="' + val.position + '"><input type="checkbox" class="fp-user fp-user-bcc positions css-checkbox" value="'+ val.position +'" id="fp-user-BCC_POSITIONS'+ val.position +'"/><label for="fp-user-BCC_POSITIONS'+ val.position +'" class="css-label"></label> <span class="limit-text-wf">'+ val.position +'</span></label>';
					                                                        ret += '</div>';
					                                                        ctr_pos++;
					                                                    }
					                                                })
					                                                
					                                            }
					                                            if(ctr_pos==0){
					                                                ret += '<span style="color:red">No Positions</span>';
					                                            }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getUsersFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Users</label>'+
									                        '</div>'+
									                        '<div class="getUsersFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var users = $(".users").text();
				                                                if(users){
				                                                    users = JSON.parse(users);
				                                                    $.each(users,function(key, val){
				                                                        ret += '<div style="width:30%;float:left;margin-bottom:2px;"> ';
				                                                            ret += '<label class="tip" title="'+ val.first_name +' '+ val.last_name +'"><input type="checkbox" class="fp-user fp-user-bcc users css-checkbox" value="'+ val.id +'" id="fp-user-bcc_users_'+ val.id +'"/><label for="fp-user-bcc_users_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.first_name +' '+ val.last_name +'</span></label>';
				                                                        ret += '</div>';
				                                                    })
				                                                }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="clearfix"></div>'+
									                '</div>'+
									            '</div>'+
									        '</div>'+
									    '</div>'+
									'</div>';
							}
							ret += '<div style="width:100%;">';
	                            ret += '<div class="fields_below">';
	                                ret += '<div class="label_below2" style="width:65%">Title: <font color="red">*</font></div>';
	                                ret += '<div class="" style="float:right;width:30%;margin: 5px 0px;font-size: 10px;font-weight: bold;">';
	                                ret += '    <label>Static: <input type="radio" name="workflow-email-title-type" class="workflow-email-title-type css-checkbox" value="0" checked="checked" id="workflow-email-title-type0"/><label for="workflow-email-title-type0" class="css-label"></label> </label>';
	                                ret += '    <label>Dynamic: <input type="radio" name="workflow-email-title-type" class="workflow-email-title-type css-checkbox" value="1" id="workflow-email-title-type1"/><label for="workflow-email-title-type1" class="css-label"></label></label>';
	                                ret += '</div>';
	                                ret += '<div class="input_position_below" style="text-align: right;">';
	                                    ret += '<input type="text" name="" class="form-text wfSettings" id="workflow-email-title" placeholder="Title" value="">';
	                                ret += '</div>';
	                            ret += '</div>';
	                        ret += '</div>';
	                        ret += '<div style="width:100%;">';
	                            ret += '<div class="fields_below">';
	                                ret += '<div class="label_below2" style="width:65%">Message: <font color="red">*</font></div>';
	                                ret += '<div class="" style="float:right;width:30%;margin: 5px 0px;font-size: 10px;font-weight: bold;">';
	                                ret += '    <label>Static: <input type="radio"  name="workflow-email-message-type" class="workflow-email-message-type css-checkbox" value="0" checked="checked" id="workflow-email-message-type0"/><label for="workflow-email-message-type0" class="css-label"></label></label>';
	                                ret += '    <label>Dynamic: <input type="radio" name="workflow-email-message-type" class="workflow-email-message-type css-checkbox" value="1" id="workflow-email-message-type1"/><label for="workflow-email-message-type0" class="css-label"></label></abel>';
	                                ret += '</div>';
	                                ret += '<div class="input_position_below" style="text-align: right;">';
	                                    ret += '<textarea class="form-textarea wfSettings" placeholder="Message" id="workflow-email-message" style="height:70px"></textarea>';
	                                ret += '</div>';
	                            ret += '</div>';
	                        ret += '</div>';
						ret += '</div>'+



































						'<div id="sms-trigger">';
							// '<h1>SMS TRIGGER</h1>'+
							{
								ret+= '<div>'+
									    '<div class="fp-container sms-users">'+
									        '<div style="width:100%;display:inline-block">'+
									            '<div style="width:30%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="sms-requestor css-checkbox" value="All Users" id="sms-requestor"><label for="sms-requestor" class="css-label"></label> Requestor</label>'+
									            '</div>'+
									            '<div style="width:50%;float:left">'+
									                '<label class="font-bold">'+
									                    '<input type="checkbox" class="sms-processor css-checkbox" value="All Users" id="sms-processor"><label for="sms-processor" class="css-label"></label> Next Processor</label>'+
									            '</div>'+
									        '</div>'+
									        '<label>'+
									            '<input type="checkbox" class="fp-allUsers css-checkbox" value="All Users" id="fp-allUsers_sms_users"><label for="fp-allUsers_sms_users" class="css-label"></label> All Users</label>'+
									        '<br>'+
									        '<div class="content-dialog-scroll2" style="position: relative; margin-left: 20px; padding: 0px; width: 100%; height: 240px;overflow: hidden;">'+
									            '<div class="ps-container">'+
									                '<div class="content-dialog2" style="width: 90%;height: auto;">'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getDepartmentFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Department</label>'+
									                        '</div>'+
									                        '<div class="getDepartmentFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                        	var departments = $(".departments").text();
						                                        var ctr_dept = 0;
						                                        if(departments){
						                                            departments = JSON.parse(departments);
						                                            $.each(departments,function(key, val){
						                                                ret += '<div style="width:30%;float:left;"> ';
						                                                //setCheckedArray(value, arr)
						                                                    ret += '<label class="tip" title="' + val.department + '"><input type="checkbox" class="fp-user fp-user-sms departments css-checkbox" value="'+ val.id +'" id="fp-user-sms_dept_'+ val.id +'"/><label for="fp-user-sms_dept_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.department +'</span></label>';
						                                                ret += '</div>';
						                                                ctr_dept++
						                                            })
						                                        }
						                                        if(ctr_dept==0){
						                                            ret += '<span style="color:red">No Department</span>';
						                                        }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="container-formUser">'+
									                        '<div class="formUser" rel="getPositionFF">'+
									                            '<label class="fa fa-minus"></label>'+
									                            '<label class="font-bold">Position</label>'+
									                        '</div>'+
									                        '<div class="getPositionFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
									                            var positions = $(".positions").text();
					                                            var ctr_pos = 0;
					                                            if(positions){
					                                                positions = JSON.parse(positions);

					                                                $.each(positions,function(key, val){
					                                                    if(val.position !=""){
					                                                        ret += '<div style="width:30%;float:left;"> ';
					                                                            ret += '<label class="tip" title="' + val.position + '"><input type="checkbox" class="fp-user fp-user-sms positions css-checkbox" value="'+ val.position +'" id="fp-user-sms_pos_'+ val.position +'"/><label for="fp-user-sms_pos_'+ val.position +'" class="css-label"></label> <span class="limit-text-wf">'+ val.position +'</span></label>';
					                                                        ret += '</div>';
					                                                        ctr_pos++;
					                                                    }
					                                                })
					                                                
					                                            }
					                                            if(ctr_pos==0){
					                                                ret += '<span style="color:red">No Positions</span>';
					                                            }
									                        ret += '</div>'+
									                    '</div>'+
									                    '<div class="clearfix"></div>'+
									                '</div>'+
									            '</div>'+
									            '<div class="container-formUser">'+
									                '<div class="formUser" rel="getUsersFF">'+
									                    '<label class="fa fa-minus"></label>'+
									                    '<label class="font-bold">Users</label>'+
									                '</div>'+
									                '<div class="getUsersFF" style="display:inline-block;width:120%;margin-left:10px;margin-top:5px;">';
							                            var users = $(".users").text();
		                                                if(users){
		                                                    users = JSON.parse(users);
		                                                    $.each(users,function(key, val){
		                                                        ret += '<div style="width:30%;float:left;margin-bottom:2px;"> ';
		                                                            ret += '<label class="tip" title="'+ val.first_name +' '+ val.last_name +'"><input type="checkbox" class="fp-user fp-user-sms users css-checkbox" value="'+ val.id +'" id="fp-user-sms_users_'+ val.id +'"/><label for="fp-user-sms_users_'+ val.id +'" class="css-label"></label> <span class="limit-text-wf">'+ val.first_name +' '+ val.last_name +'</span></label>';
		                                                        ret += '</div>';
		                                                    })
		                                                }
							                        ret += '</div>'+
									            '</div>'+
									        '</div>'+
									    '</div>'+
									    '<div style="width:100%;">'+
									        '<div class="fields_below">'+
									            '<div class="label_below2">Other Recipient: <font color="red">*</font>'+
									            '</div>'+
									            '<div class="input_position_below" style="text-align: right;">'+
									                '<input type="text" name="" class="form-text tip" title="" id="workflow-sms-contact" placeholder="Title" value="" data-original-title="Number should be Semicolon separated">'+
									            '</div>'+
									        '</div>'+
									    '</div>'+
									    '<div style="width:100%;">'+
									        '<div class="fields_below">'+
									            '<div class="label_below2">Message: <font color="red">*</font>'+
									            '</div>'+
									            '<div class="" style="">'+
									                '<label>Static: '+
									                    '<input type="radio" checked="checked" name="workflow-sms-message-type" class="workflow-sms-message-type css-checkbox" value="0" id="workflow-sms-message-type0"><label for="workflow-sms-message-type0" class="css-label"></label>'+
									                    '</label>'+
									                        '<label>Dynamic: '+
									                            '<input type="radio" undefined="" name="workflow-sms-message-type" class="workflow-sms-message-type css-checkbox" value="1" id="workflow-sms-message-type1"><label for="workflow-sms-message-type1" class="css-label"></label>'+
									                            '<label></label>'+
									                        '</label>'+
									                    '</label>'+
									                '</label>'+
									            '</div>'+
									            '<div class="input_position_below" style="text-align: right;">'+
									                '<textarea class="form-textarea wfSettings" placeholder="Message" id="workflow-sms-message" style="height:70px"></textarea>'+
									            '</div>'+
									        '</div>'+
									    '</div>'+
									'</div>';
							}
						ret += '</div>'+





						'<div class="fields">'+
							'<div class="label_basic"></div>'+
							'<div class="input_position rule_dialog_button_actions" style="margin-top:5px;text-align:right;">'+
								'<img src="/images/loader/load.gif" class="display saveFormLoad" style="margin-right:5px;margin-top:2px;"/>'+
								((opts["action_button"])?opts["action_button"].join(""):"")+
								'<input type="button" class="btn-basicBtn fl-buttonEffect" id="popup_cancel" value="Cancel">'+
							'</div>'+
						'</div>'+
						
					'</div>'+
				'</div>'+
			'</form>'+
		'</div>'+
		'<input type="text" class="middlewareFormFields display">'+
	'</div>';

	var newDialog = new jDialog(ret, "", "1024", "", "", function() {  });
	newDialog.themeDialog("modal2",{"height":"450"});

	var pop_container = $("#popup_container");

	//dialog fixes 
	pop_container.find("[id='content-dialog-scroll']").eq(0).css("height","500px");
	if(typeof cB == "function"){
		cB.call(pop_container);
	}
	

}



































// function getFormFields



// if($('.workflow-ref-field').length >= 1 ){
// 	$('.workflow-ref-field').each(function(){
// 		$(this).html(collect_append_option);
// 	});
// }
// if($('.workflow-trigger-fields-filter').length >= 1){
// 	$('.workflow-trigger-fields-filter').each(function(){
// 		$(this).html(collect_append_option);
// 	});
// }
// if($('.workflow-trigger-fields-update').length >= 1){
// 	$('.workflow-trigger-fields-update').each(function(){
// 		$(this).html(collect_append_option);
// 	});
// }